﻿/*******************************************************************************

INTEL CORPORATION PROPRIETARY INFORMATION
This software is supplied under the terms of a license agreement or nondisclosure
agreement with Intel Corporation and may not be copied or disclosed except in
accordance with the terms of that agreement
Copyright(c) 2013 Intel Corporation. All Rights Reserved.

*******************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ImageGallery
{
    class VoiceSynthesis
    {
        public static string Speak(string module, uint language, string sentence)
        {
            PXCMSession session;
            if (PXCMSession.CreateInstance(out session) < pxcmStatus.PXCM_STATUS_NO_ERROR)
                return "Failed to create an SDK session";

            PXCMSession.ImplDesc desc=new PXCMSession.ImplDesc();
            desc.friendlyName.set(module);
            desc.cuids[0]=PXCMVoiceSynthesis.CUID;
            PXCMVoiceSynthesis vsynth;
            if (session.CreateImpl<PXCMVoiceSynthesis>(ref desc,PXCMVoiceSynthesis.CUID, out vsynth)< pxcmStatus.PXCM_STATUS_NO_ERROR) {
                session.Dispose();
                return "Failed to create the synthesis module";
            }

            PXCMVoiceSynthesis.ProfileInfo pinfo;
            vsynth.QueryProfile(language,out pinfo);
            if (vsynth.SetProfile(ref pinfo)<pxcmStatus.PXCM_STATUS_NO_ERROR) {
                vsynth.Dispose();
                session.Dispose();
                return "Failed to initialize the synthesis module";
            }

            int tid=0;
            vsynth.QueueSentence(sentence,out tid);
            VoiceOut vo=new VoiceOut(pinfo.outputs.info);
            for (;;) {
                PXCMAudio sample;
                PXCMScheduler.SyncPoint sp;

                if (vsynth.ProcessAudioAsync(tid,out sample, out sp)<pxcmStatus.PXCM_STATUS_NO_ERROR) break;
                pxcmStatus sts=sp.Synchronize();
                vo.RenderAudio(sample);
                sample.Dispose();
                sp.Dispose();
                if (sts<pxcmStatus.PXCM_STATUS_NO_ERROR) break;
            }
            vo.Close();

            vsynth.Dispose();
            session.Dispose();
            return null;
        }
    }
}
